import { getToken, removeExpiresIn, removeToken, setExpiresIn, setMyCart, setToken } from '../../utils/auth'
import loginApi from '../../api/login'
import memberApi from '../../api/member'

const user = {
  state: {
    token: getToken(),
    userInfo: null // 用户信息
  },
  mutations: {
    // 设置token
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    // 设置过期时间
    SET_EXPIRES_IN: (state, time) => {
      state.expires_in = time
    },
    // 设置用户信息
    SET_USER_INFO: (state, userInfo) => {
      state.userInfo = userInfo
    }
  },
  actions: {
    // 登录操作
    Login ({ commit }, loginInfo) {
      const phone = loginInfo.phone.trim()
      const password = loginInfo.password
      const code = loginInfo.code
      const uuid = loginInfo.uuid
      return new Promise((resolve, reject) => {
        loginApi.login({
          phone, password, code, uuid
        }).then(res => {
          // console.log(res)
          const { access_token, expires_in } = res.data
          setToken(access_token)
          commit('SET_TOKEN', access_token)
          setExpiresIn(expires_in)
          commit('SET_EXPIRES_IN', expires_in)
          resolve(res)
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 获取客户登录信息
    GetInfo ({ commit, state }) {
      return new Promise(((resolve, reject) => {
          memberApi.getInfo().then(res => {
            const userInfo = res.data
            commit('SET_USER_INFO', userInfo)
            resolve(res)
          }).catch(error => {
            reject(error)
          })
        })
      )
    },
    // 退出
    LogOut ({ commit, state }) {
      return new Promise(((resolve, reject) => {
        loginApi.logout().then(res => {
          commit('SET_TOKEN', null)
          commit('SET_EXPIRES_IN', null)
          commit('SET_USER_INFO', null)
          commit('REMOVE_CART_ALL')
          removeToken()
          removeExpiresIn()
          resolve()
        }).catch(error => {
          reject(error)
        })
      }))
    }
  }
}

export default user
